package org.nanyuan.forum.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.config.AppConfig;
import org.nanyuan.forum.model.Article;
import org.nanyuan.forum.model.Board;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IArticleService;
import org.nanyuan.forum.service.IBoardService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布帖子
     */
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("boardId") @NotNull String boardId,
                            @RequestParam("title") @NotNull String title,
                            @RequestParam("content") @NotNull String content) {

        //校验用户是否处于禁言状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //禁言状态
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //非空校验
        Board board = boardService.selectById(Long.valueOf(boardId));
        if (board == null || board.getDeleteFlag() == 1 || board.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);  //标题
        article.setContent(content);  //正文
        article.setBoardId(Long.valueOf(boardId));  //板块id
        article.setUserId(user.getId());   //作者id

        //调用service
        articleService.create(article);

        //返回响应
        return AppResult.success();
    }


    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false) Long boardId) {

        //定义返回的结果集
        List<Article> articles;
        //判断此次查询的情况
        if (boardId == null) {
            //查询所有
             articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        //判断结果是否为空
        if (articles == null) {
            //如果为空，创建一个空集合
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    /*
    * 根据帖子id获取帖子详情
    * */
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @RequestParam("id") @NonNull Long id) {
        //从session中获取当前的登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service，获取帖子详情
        Article article = articleService.selectDetailById(id);
        //对结果进行非空校验
        if (article == null) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (user.getId().equals(article.getUserId())) {
            //标记为作者
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    /*
    * 根据id更新帖子
    * */
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content) {
        //获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if (user.getState() == 1) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断当前用户是不是作者
        if (!user.getId().equals(article.getUserId())) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //判断帖子的状态
        if (article.getState() == 1 || article.getDeleteFlag() == 1) {
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED);
        }
        //调用service
        articleService.modify(id,title,content);
        //打印日志
        log.info("帖子更新成功，Article id：{}，User id：{}.",id,user.getId());

        return AppResult.success();
    }

    /*
    * 点赞
    * */
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request

                             ,@RequestParam("id") @NonNull Long id) {
        //获取已登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //对当前用户状态进行校验
        if (user.getState() == 1) {
            //返回提示信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service
        articleService.thumbsUpById(id);
        //返回成功信息
        return AppResult.success();
    }
    @PostMapping("/deleteById")
    public AppResult deleteById(HttpServletRequest request,
                                @RequestParam("id") @NonNull Long id) {
        //获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //获取帖子详情
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteFlag() == 1) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //校验当前用户是否为作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用Service
        articleService.deleteById(id);
        //返回成功信息
        return AppResult.success("删除成功");

    }

    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
            @RequestParam(value = "userId",required = false) Long userId) {

        //如果userid为空，从session中获取当前的登录用户的用户id
        if (userId == null) {
            //获取session
            HttpSession session = request.getSession(false);
            //从session中获取用户id
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);

        return AppResult.success(articles);
    }
}
